package com.nit.lab.service.basic.impl;


import com.nit.lab.dto.basic.StaffDTO;
import com.nit.lab.dto.utils.PagingDTO;
import com.nit.lab.dto.utils.TableReqDTO;
import com.nit.lab.dto.utils.TableRspDTO;
import com.nit.lab.entity.basic.StaffEntity;
import com.nit.lab.mapper.basic.StaffMapper;
import com.nit.lab.service.basic.StaffService;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class StaffServiceImpl implements StaffService {

    private final StaffMapper staffMapper;

    @Autowired(required = false)
    public StaffServiceImpl(StaffMapper staffMapper) {
        this.staffMapper = staffMapper;
    }


    @Override
    public TableRspDTO list4Table(TableReqDTO tableReqDTO) throws Exception {
        Long count = staffMapper.count4Table(
                tableReqDTO.parseQueryParam("staffName"),
                tableReqDTO.parseQueryParam("deptId"));
        PagingDTO pagingDTO = new PagingDTO(
                tableReqDTO.getPageNo(),
                tableReqDTO.getPageSize(),
                count,
                staffMapper.list4Table(
                        tableReqDTO.getStart(),
                        tableReqDTO.getPageSize(),
                        tableReqDTO.parseQueryParam("staffName"),
                        tableReqDTO.parseQueryParam("deptId"),
                        tableReqDTO.getSortField(),
                        tableReqDTO.getSortOrder()));
        TableRspDTO tableRspDTO = new TableRspDTO(pagingDTO);
        return tableRspDTO;
    }

    @Override
    public Integer add(StaffDTO staffDTO) throws Exception {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        StaffEntity staffEntity = mapperFactory.getMapperFacade().map(staffDTO, StaffEntity.class);
        staffEntity.setGmtCreate(new Date());
        return staffMapper.add(staffEntity);
    }

    @Override
    public Integer update(StaffDTO staffDTO) throws Exception {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        StaffEntity staffEntity = mapperFactory.getMapperFacade().map(staffDTO, StaffEntity.class);
        return staffMapper.update(staffEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer remove(String staffIds) throws Exception {
        String[] arrayStaffId = staffIds.split(",");
        for (int i = 0; i < arrayStaffId.length; i++) {
            staffMapper.remove(Long.parseLong(arrayStaffId[i]));
        }
        return arrayStaffId.length;
    }


    @Override
    public StaffDTO getStaffById(Long staffId) throws Exception {
        return staffMapper.getStaffById(staffId);
    }
}
